package com.region.http.client.core;

import com.region.common.utils.ClassUtils;
import com.region.http.client.annotation.configurer.LocalConfigurer;
import com.region.http.client.annotation.configurer.LocalConfigurer.Protector;
import com.region.http.client.model.RequestMeta;
import com.region.http.client.protector.RequestProtector;

import java.lang.annotation.Annotation;

/**
 * @author 26225
 * @date 2024/8/31 16:21
 * @description
 */
public class LocalConfigurerMetaResolver implements MetaResolver {
    @Override
    public void doResolver(RequestMeta.RequestMetaBuilder builder, Annotation annotation, MetaChain chain) {
        if (annotation instanceof LocalConfigurer) {
            LocalConfigurer configurer = (LocalConfigurer) annotation;
            builder.connectTime(configurer.connectTime());
            builder.readTime(configurer.readTime());
            builder.requestTime(configurer.requestTime());
            builder.executor(configurer.executor());
            LocalConfigurer.Protector[] protectors = configurer.protectors();
            if (protectors != null && protectors.length > 0) {
                Protector protector = protectors[0];
                Class<? extends RequestProtector> fallbackClass = protector.fallbackClass();
                if (fallbackClass != RequestProtector.class && RequestProtector.class.isAssignableFrom(fallbackClass)) {
                    builder.intervalTime(protector.intervalTime());
                    builder.exceedsTime(protector.exceedsTime());
                    builder.protector(fallbackClass);
                    if (!Registers.getInstance().existsProtector(fallbackClass)) {
                        Registers.getInstance().registerProtector(ClassUtils.newInstance(fallbackClass));
                    }
                }
            }
        }
        chain.doResolver(builder, annotation);
    }

}
